<template>
    <div class="app-container" style="height: 680px;">
        <!-- 列表查询 -->
        <el-table v-loading="loading" :data="classList"  @selection-change="handleSelectionChange" :header-cell-style="{ background: '#eee', color: '#909399' }">
                <template #empty v-if="classList.length == 0">
                <el-empty description="暂时还没有班级信息哦~" />
               </template>
                <el-table-column label="编号" align="center" key="classId" prop="classId" />
                <el-table-column label="班级名称">
                  <template #default="scope">
                     <el-tooltip class="box-item" effect="dark" content="点击查看" placement="top">
                    <span @click="classonclick(scope.row)" style="cursor: pointer;" class="class_style">{{ scope.row.className }}</span>
                     </el-tooltip>
                  </template>
                 </el-table-column>
                <el-table-column label="阶段名称" align="center" key="levelName" prop="levelName" :show-overflow-tooltip="true" />
                <el-table-column label="目前所在" align="center" key="name" prop="name" :show-overflow-tooltip="true" />
                <el-table-column label="所在讲师" align="center" key="nickname" prop="nickname" :show-overflow-tooltip="true" />
                <el-table-column label="创建时间" align="center" key="createTimeS1" prop="createTimeSl" :show-overflow-tooltip="true" />
                <el-table-column label="修改时间" align="center" key="createTimeSl" prop="createTimeSl" :show-overflow-tooltip="true"/>
             </el-table>
    </div>
   
    <!-- 新增弹框 -->
    <el-dialog
    style="border-radius: var(--el-border-radius-base);"
    v-model="centerDialogVisible"
    :title="titles"
    width="500"
    align-center>

    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" status-icon :rules="rules" label-width="auto" class="demo-ruleForm">


        <el-form-item label="换班的名称" prop="className">
            <el-input  v-model="ruleForm.className" disabled/>
        </el-form-item>

    <el-form-item label="要带班级" prop="className">
        <el-tree-select
       accordion="true"
       v-model="ruleForm.new_classId"
       :props="{ label: 'name', children: 'children',value:'id'}"
       :data="cacheData"
       style="width: 240px"
       />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm_class(ruleFormRef)">
        确认
      </el-button>
      &nbsp;&nbsp;&nbsp;
      <span v-if="titles != '修改班级'">
        <el-button @click="resetForm_class(ruleFormRef)">重置</el-button>
      </span>
    </el-form-item>
  </el-form>
  </el-dialog>

   <!-- 学生查询弹框 -->
   <el-dialog
    style="border-radius: var(--el-border-radius-base);"
    v-model="centerDialogVisible_student"
    :title="class_titles"
    width="1200"
    align-center>
    <div style="margin-left: 3.5%;">
        <span v-if="stuarray.length>0">
        <el-card style="max-width: 260px; display: inline-block;  margin: 5px;" v-for="stu in stuarray">

          <el-row :gutter="20">
            <el-tooltip content="删除学生" placement="top">
               <el-button link type="primary" icon="Close" @click="studentDelete(stu.userId)" v-hasPermi="['system:user:resetPwd']" style="position: relative; left: 225px; top: -30px;"></el-button>
            </el-tooltip>
           <span @click="student_Info(stu)"> <el-tooltip content="点击查看" placement="top"><el-avatar :size="50" :src="stu.avatar"/></el-tooltip></span>
         <el-text class="mx-1" style="position: relative; top: -6px; left: 5px">姓名：{{stu.nickname}}</el-text>
        </el-row>
        <el-link icon="edit" style="position: relative; left: 73%; top: 14.5px;" class="diaoban" @click="studentEdit(stu)">调班</el-link>
       </el-card>
       <el-pagination     
     v-model:current-page="currentPage4"
     v-model:page-size="pageSize4"
     :page-sizes="[5, 10, 15, 20]"
     layout="total, sizes, prev, pager, next, jumper"
     :total="total"
     @size-change="handleSizeChange"
     @current-change="handleCurrentChange"
     background
   />
      </span>
      <span v-else>
        <el-empty description="该班级还没有学生哦~"/>
      </span>
    </div>
   </el-dialog>
    <!-- 学生调班查询弹框 -->
    <el-dialog
    style="border-radius: var(--el-border-radius-base);"
    v-model="centerDialogVisible_student_diaoban"
    :title="class_titles_student"
    width="300"
    align-center>
    <el-tree
    expand-on-click-node="true"
     accordion="true"
     :data="deptOptions"
     :props="{ label: 'name', children: 'children',value:'id'}"
     node-key="id"
     highlight-current
     @node-click="handleNodeClick"
    />
<el-button @click="query_student_class">确认</el-button>
<el-button @click="centerDialogVisible_student_diaoban = false">取消</el-button>
    </el-dialog>
 </template>
 
 <script setup name="User">
import { getTokeName } from "@/utils/comstants";
import { reactive, ref, toRefs,watch } from "vue";
import { findAll_class,findStudentByClass,addOrUpdaclass,delclass,download,levelall,allteacher,changeclass,findClassById } from "@/api/admin/class/class_api";
import { teacher_class,getStudentExam } from "@/api/teacher/class/teacher_class";
import { delBatchStudent,stu_list_tree } from "@/api/admin/student/student_api.js"
import { ElMessage,ElMessageBox,ElTree } from "element-plus";
import { useUserStore1 } from '@/store/userStore.js';
import { useRouter } from 'vue-router';
const router = useRouter()
// import router from "@/router";

import { useStudentStore1 } from "@/store/studentInfo";

const userInfo = useUserStore1().userInfo;

const queryRef=ref()
const ruleFormRef = ref()
const showSearch = ref(true); //动态隐藏
const classList = ref([]);//班级列表
const loading =ref(true)//页面加载
const titles=ref('')
const class_titles = ref('')
const centerDialogVisible = ref(false);//新增修改弹框
const centerDialogVisible_student = ref(false)//学生查询弹框
const centerDialogVisible_student_diaoban = ref(false)//学生调班
const class_titles_student = ref("选择要调换班级")//学生调班提示
const teachercities = ref([])//讲师数组
const levelIdcities = ref([])//阶段数组
const deptOptions=ref([]) //三级菜单

//属性查询方法
function treefunlist(){
   loading.value=true
  stu_list_tree().then(res=>{
   loading.value=false
    deptOptions.value=res.data.obj
  })
}
const cacheData = ref([])

stu_list_tree().then(res=>{
   cacheData.value=res.data.obj[0].children
})


const datanum = []  
const class_info = ref()
//多选
const handleSelectionChange = (val) => {
    datanum.splice(0,datanum.length);
    val.forEach(element => {
        datanum.push(element.classId)
    });
    //说明用户选择1条数据
    if(datanum.length == 1){
        class_info.value=val
    }
}



//查询列表
function getList(){
   loading.value = true
   teacher_class(userInfo.userId).then(res=>{
      loading.value = false
      classList.value=res.data.obj
      classList.value.forEach(element => {
         //创建时间格式化
      if(element.createTimeSl !=null){
       element.createTimeSl=caseTime(element.createTimeSl)
      }
      //修改时间格式化
      if(element.updateTimeSl !=null){
       element.updateTimeSl=caseTime(element.updateTimeSl)
      }
      });
   })
}
//添加或修改数据
const ruleForm = ref({
     new_classId:'',
     className:'',
})


//新增初始化方法
function handleAdd(){
   ruleForm.value={}//清空
   centerDialogVisible.value=true
   titles.value='新增班级';
}
//修改初始化方法
function handleUpdate(row){
   ruleForm.value={}//清空
   if(datanum.length == 1){
       centerDialogVisible.value=true
      titles.value='修改班级';
      ruleForm.value=class_info.value[0]
   }else if(row.classId != null){
      centerDialogVisible.value=true
      titles.value='修改班级';
      ruleForm.value=row
   }else{
      ElMessage.warning("请选择一个班级哦")
   }
}

//添加和修改
function submitForm_class(formEl){
   if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
    addOrUpdaclass(ruleForm.value).then(res=>{
         if(res.data.code == 200){
            centerDialogVisible.value=false
             ElMessage.success('操作成功');
             getList();
         }else{
            ElMessage.error(res.data.message)
         }
      })

    } 
  })
}

//删除方法
function handleDelete(row){
   ElMessageBox.confirm(
    '您确认要删除嘛?',
    '温馨提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
     if(datanum.length>0){    //删除方法
        delclass(datanum).then(res=>{
         if(res.data.code == 200){
            ElMessage.success("删除成功");
            getList();
         }else{
           ElMessage.error("删除失败");
         }
      })
     }else if(row.classId != null){
        delclass(row.userId).then(res=>{
         if(res.data.code == 200){
            ElMessage.success("删除成功");
            getList();
         }else{
           ElMessage.error("删除失败");
         }
      })
     }else{
      ElMessage.warning("请至少选择一个")
     }
     
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
}

//重置添加或者修改
const resetForm_class = (formEl) => {
   ruleForm.value = {}
  if (!formEl) return
  formEl.resetFields()
}

/**时间转换 */
function caseTime(date){
    let time=new Date(date);
    let year=time.getFullYear();
    let month=time.getMonth()+1;
    let day=time.getDate()+1;
    let hours=time.getHours();
    let minutes=time.getMinutes();
    if(month<=9){
        month='0'+month
    }

    if(day<=9){
       day='0'+day
    }

    if(hours<=9){
      hours='0'+hours
    }
    if(minutes<=9){
      minutes='0'+minutes
    }
    return year+"-"+month+"-"+day+" "+hours+":"+minutes;
}
//阶段查询所有
function level_list(){
    levelall().then(res=>{
    levelIdcities.value=res.data.obj
   })
}
//老师查询所有
function teacher_list(){
   allteacher().then(res=>{
    teachercities.value=res.data.obj
   })
}

const props = defineProps({
   /* 是否显示检索条件 */
   showSearch: {
      type: Boolean,
      default: true,
   },
   /* 显隐列信息 */
   columns: {
      type: Array,
   },
   /* 是否显示检索图标 */
   search: {
      type: Boolean,
      default: true,
   },
   /* 显隐列类型（transfer穿梭框、checkbox复选框） */
   showColumnsType: {
      type: String,
      default: "checkbox",
   },
   /* 右外边距 */
   gutter: {
      type: Number,
      default: 10,
   },
})

const emits = defineEmits(['update:showSearch', 'queryTable']);

//根据班级id查询旗下学生信息
const  stuarray = ref([])
const total = ref()
const currentPage4 = ref(1)
const pageSize4 = ref(8)
const sel_classByid = ref()

function classonclick(row){
   class_titles.value=row.className+"班学生📖【带班讲师："+row.nickname+"】📖【目前阶段："+row.name+"】"
    currentPage4.value=1
     pageSize4.value=8
     class_studeninfo.value.pageNum=1
     class_studeninfo.value.pageSize=8
     class_studeninfo.value.classId=row.classId
    tea_class_students()
    sel_classByid.value=row.classId
    centerDialogVisible_student.value=true  //打开弹框
}

const class_studeninfo = ref({
   pageNum:currentPage4.value,
   pageSize:pageSize4.value,
   classId:''
})

function  tea_class_students(){
   findStudentByClass(class_studeninfo.value).then(res=>{
         if(res.data.code == 200){
            stuarray.value=res.data.obj.list
            total.value=res.data.obj.total
         }
    })
}

//控制条数
const handleSizeChange = (val) => {
   class_studeninfo.value.pageSize=val
   tea_class_students()
}
//控制页数
const handleCurrentChange = (val) => {
   class_studeninfo.value.pageNum=val
   tea_class_students()
}

const studentparam=ref({
   pageNum:1,
   pageSize:5,
})

//删除学生
function studentDelete(id){
   ElMessageBox.confirm(
    '您确认要删除嘛?',
    '温馨提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      delBatchStudent(id).then(res=>{
         if(res.data.code == 200){
            ElMessage.success("删除成功");
            stuarray.value=[] //刷新
            //刷新学生数组
            findClassById(sel_classByid.value).then(res=>{
            stuarray.value=res.data.obj
         })
         }else{
           ElMessage.error("删除失败");
         }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
}
const userId = ref()
//换班
function studentEdit(row){
    treefunlist()
    userId.value=row.userId
    centerDialogVisible_student_diaoban.value=true
}
const classId = ref()
//阶段名称根据班级查询学生方法
function handleNodeClick(data){
   if(data.id != 1 && data.id != 2 && data.id != 3 && data.id != 4){
      classId.value=data.classId   //赋值班级id
   }
}

/*确认调班方法*/
function query_student_class(){
   changeclass(userId.value,classId.value).then(res=>{
      if(res.data.code == 200){
         ElMessage.success("调班成功");
         centerDialogVisible_student_diaoban.value=false//关闭弹框
          //刷新学生数组
          findClassById(sel_classByid.value).then(res=>{
            stuarray.value=res.data.obj
         })
      }else{
         ElMessage.error(res.data.message)
      }
   })
}

//学生个人信息查询
function student_Info(row){
     useStudentStore1().setStudentInfo(row)
     router.push("/teacher/studentInfo")
}

// 刷新
function refresh() {
    // alert(111)
  getList()
}

getList()
level_list()
teacher_list()

 </script>
 <style>
.button_clss{
   width: 73px;
   height: 28px;
}
.el-card__body{
    width: 260px;
}
.diaoban{
    color: #79bbff;
}
.diaoban:hover{
    color: rgb(255, 0, 0);
}
.class_style{
   color:  #eebe77;
}
.class_style:hover{
   color:  #606266;
}
</style>
 